<template>
  <div class="app-container">
    <el-col :span="13">
      <el-col :span="4">
        <el-tag color="white">门诊医技工作台</el-tag>
      </el-col>
      <el-col :span="16" :offset="1">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item prop="name">
            <el-input
              v-model="queryParams.keyword"
              placeholder="病历号/姓名"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-col>

      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>

    <el-table v-loading="loading" :data="non_drug_item_recordList" @selection-change="handleSelectionChange">
      <el-table-column label="病历号" width="220px" align="center" prop="patient.medicalRecordNo" />
      <el-table-column label="姓名" width="80px" align="center" prop="patient.name" />
      <el-table-column label="年龄" width="160px" align="center" prop="registration.patientAgeStr" />
      <el-table-column label="性别" width="60px" align="center" prop="patient.gender" >
      <template slot-scope="scope">
        {{formatIfPass[scope.row.patient.gender]}}
      </template>
      </el-table-column>
      <el-table-column label="开立项目" width="220px" align="center" prop="nonDrug.name" />
      <el-table-column label="检查部位" align="center" prop="checkParts" />
      <el-table-column label="状态" width="80px" align="center" prop="status" >
        <template slot-scope="scope">
        <el-tag :type='onColourLine[scope.row.status]'>{{onLine[scope.row.status]}}</el-tag>
      </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status==2"
            v-hasPermi="['dms:non_drug_item_record:edit']"
          >登记</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleBulu(scope.row)"
            v-if="scope.row.status==2"
            v-hasPermi="['dms:non_drug_item_record:remove']"
          >补录</el-button>
          <el-button
            type="primary"
            size="small"
            v-if="scope.row.status==3"
            @click="handleAddCheckResult(scope.row)"
            v-hasPermi="['dms:non_drug_item_record:edit']"
          >上传结果</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改检查项检验项处置项记录(开立的)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="检查结果">
          <el-input v-model="form.checkResult" prop="checkResult" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <el-dialog :title="titletwo" :visible.sync="isShow" width="500px" append-to-body>
        <el-upload
          title="点击上传文件"
          :action="ossHost"
          :data="ossData"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-upload="beforeUpload">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button type="primary" size="mini" @click="cancelOn">确 定</el-button>
          <el-button type="primary" size="mini" @click="clearFiles">取 消</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" size="mini" icon="el-icon-upload" @click="cancel">上传图片</el-button>
        <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="addMed" append-to-body width="1200px">
      <el-form :inline="true" :model="formPre" :rules="rules" ref="formPre">
        <el-row>
          <el-col :span="6" :xs="24">
            <div class="head-container">
              <el-row>
                <el-col :span="16">
                  <el-input
                    v-model="drug.name"
                    placeholder="请输入药品名称"
                    clearable
                    size="small"
                    prefix-icon="el-icon-search"
                    style="margin-bottom: 5px"
                  />
                </el-col>
                <el-col :span="8">
                  <el-button type="cyan" icon="el-icon-search" size="mini" @click="getDrugList()" style="float: right">搜索</el-button>
                </el-col>
              </el-row>

            </div>
            <div class="head-container">
              <el-table v-loading="loading" :row-style="{height: '10px'}" :cell-style="{padding:'0px'}" :data="drugList" @row-click="addDrug"stripe style="height: 400px;max-height: 700px;overflow: auto;">
                <el-table-column label="ID" align="center" prop="id" v-if="false"/>
                <el-table-column  align="center"  label="药品名" prop="name">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" :content="scope.row.name"  placement="right-start">
                      <p style="height:25px;overflow: hidden;text-align: center;border: none">{{ scope.row.name }}</p>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column label="价格(元)" align="center" prop="price" />
              </el-table>
              <pagination
                layout="prev, pager, next"
                :limit.sync="drug.pageSize"
                :page-sizes=null
                :page.sync="drug.pageNum"
                :total="total"
                @pagination="getDrugList"
                small
                v-show="total>0"
              />
            </div>
          </el-col>
          <el-col :span="16">
            <div style="margin-left: 10px">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="补录处方名">
                    <el-input v-model="formPre.name" placeholder="请输入补录处方名"/>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="补录处方类型">
                    <el-select v-model="formPre.scope" placeholder="请选择补录处方类型" @change="handleQueryPre">
                      <el-option
                        v-for="dict in types"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="parseInt(dict.dictValue)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <el-button @click="submit()" type="primary">补录处方开立</el-button>
                </el-col>
              </el-row>
              <el-tag disabled plain type="primary">项目金额总计:</el-tag>
              <el-tag disabled plain type="warning">{{this.formPre.amount}}元</el-tag>
              <el-table :data="prescriptionDrugList" style="max-height: 450px;overflow: auto;" width="600px">
                <el-table-column align="center" prop="del">
                  <template slot-scope="scope">
                    <a @click="del(scope.$index,scope.row)">删除</a>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="药品id" prop="drugId" v-if="false"/>
                <el-table-column align="center" label="药品名" prop="name"/>
                <el-table-column align="center" label="规格" prop="format" v-if="false"/>
                <el-table-column align="center" label="单价" prop="price"/>
                <el-table-column align="center" label="数量" width="150px" prop="num">
                  <template slot-scope="scope">
                    <el-input-number :max="10" :min="1" @change="amountSettlement" size="mini"
                                     v-model="prescriptionDrugList[scope.$index].num"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="使用方法">
                  <template slot-scope="scope">
                    <el-select id="medicineUsage" placeholder="方法" size="small"
                               v-model="prescriptionDrugList[scope.$index].medicineUsage">
                      <el-option
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                        v-for="dict in methodOptions"
                      />
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listNon_drug_item_record, getNon_drug_item_record, delNon_drug_item_record, addNon_drug_item_record, updateNon_drug_item_record, exportNon_drug_item_record, updateNon_drug_item_record_check_result,updateNon_drug_item_record_status } from "@/api/dms/non_drug_item_record";
import {
  addMedicine_prescription_record,
  delMedicine_prescription_record_all
} from "@/api/dms/medicine_prescription_record";
import {
  addHerbal_prescriptionBulu
} from "@/api/dms/herbal_prescription_record";
import{listDrug,getDrug,getDrugType} from "@/api/dms/drug";
import { getRegistration, updateRegistration} from "@/api/dms/registration";
import {listUsed} from "@/api/dms/used";
import {policy} from '@/api/upload'
// 导入uuid库
import uuidv4 from 'uuid/v4'

export default {
  name: "Non_drug_item_record",
  data() {
    return {
      methodOptions: [],
      registrationId: null,
      nonId: null,
      /**补录处方id*/
      prescriptionId:undefined,
      /**补录处方类型*/
      types:{},
      //药品参数
      drug: {
        pageNum: 1,
        pageSize: 10,
        typeId: -103,
        name: null
      },
      //药品集合
      drugList: [],
      //常用成药集合
      usedMedicineList: [],
      //处方药品集合
      prescriptionDrugList: [],
      addMed: false,
      titletwo:'',
      isShow: false,
      dialogImageUrl: '',
      dialogVisible: false,
      ossHost: '',
      ossData: {},
      // 状态的对应的值
      onLine: {"0": "作废", "1": "未缴费", "2": "未登记", "3": "已登记", "4":"已执行", "5":"已退费", "6":"已过期"},
      // 状态的对应的颜色
      onColourLine: {"0": "warning", "1": "success", "2": "info", "3": "", "4":"", "5":"", "6":"warning"},
      //性别
      formatIfPass: {
        "0": "女", "1": "男",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检查项检验项处置项记录(开立的)表格数据
      non_drug_item_recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null
      },
      // 表单参数
      formPre: {
        amount: 0,
        status: 1,
        name: null,
        registrationId: null,
        dmsHerbalItemRecord: [],
        medicineItemRecords: []
      },
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("drug_usageNumUnit").then(response => {
      this.usageNumUnitList = response.data;
    });
    this.getDicts("prescription_type").then(response => {
      this.types = response.data;
    });
    this.getDicts("drug_use_method").then(response => {
      this.methodOptions = response.data;
    });
  },
  methods: {
    /** 选中处方操作 */
    handleQueryPre() {
      this.prescriptionId = this.formPre.scope;
      getDrugType(this.formPre.id,this.prescriptionId).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          response.data[i].drugId = response.data[i].id;
        }
        this.prescriptionDrugList = response.data;
      });
      if(this.prescriptionId == 1){
        this.drug.typeId = 102;
      }else if(this.prescriptionId == 2){
        this.drug.typeId = 103;
      }
      this.getDrugList();
    },
    //获取成药列表
    getDrugList() {
      listDrug(this.drug).then(value => {
        this.drugList = value.rows;
        this.total = value.total;
      });
    },
    /**点击添加药品*/
    addDrug(row, event, column) {
      if (this.drugCheck(row.id)) {
        getDrug(row.id).then(value => {
          this.prescriptionDrugList.push({
            drugId: parseInt(value.data.id),
            name: value.data.name,
            format: value.data.format,
            price: value.data.price,
            usageNumUnit: value.data.dosageId,
            status:1,
            num: 1
          });
          this.amountSettlement();
        });
      }
    },
    /**药品查重*/
    drugCheck(id) {
      let list = this.prescriptionDrugList;
      for (let i = 0; i < list.length; i++) {
        if (id === list[i].drugId) {
          list[i].num += 1;//如果药品重复，就在数量上加一
          this.amountSettlement();
          return false;
        }
      }
      return true;
    },
    /**金额结算*/
    amountSettlement() {
      let price = 0;
      this.prescriptionDrugList.forEach(value => {
        price += value.price * value.num;
      });
      this.formPre.amount = price;
    },
    /**删除*/
    del(index, row) {
      this.prescriptionDrugList.splice(index, 1);
      this.amountSettlement();
    },
    /**赋值给form中的数组*/
    set() {
      this.formPre.registrationId = this.registrationId;
      this.formPre.dmsHerbalItemRecord = this.prescriptionDrugList;
      this.formPre.medicineItemRecords = this.prescriptionDrugList;
    },
    /**补录处方开立*/
    submit() {
      this.set();
      this.$refs["formPre"].validate(valid => {
        if (valid) {
          if(this.formPre.scope==1){
            delMedicine_prescription_record_all(this.registrationId,this.formPre.id);
            addMedicine_prescription_record(this.formPre).then(response => {
              if (response.code === 200) {
                updateNon_drug_item_record_status(this.formPre);
                this.msgSuccess("补录处方开立成功！请缴费后再登记");
                this.addMed = false;
                this.getList();
              }
            });
          }else if(this.formPre.scope==2){
            addHerbal_prescriptionBulu(this.formPre).then(response => {
              if (response.code === 200) {
                updateNon_drug_item_record_status(this.formPre);
                this.msgSuccess("补录处方开立成功！请缴费后再登记");
                this.addMed = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 查询检查项检验项处置项记录(开立的)列表 */
    getList() {
      this.loading = true;
      listNon_drug_item_record(this.queryParams).then(response => {
        this.non_drug_item_recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    clearFiles () {
      if(this.dialogImageUrl!=null){
        this.$refs.upload.clearFiles();
      }
      this.dialogImageUrl = '';
      this.ossData.key = '';
      this.form.resultImgUrlList = null;
      this.isShow = false;
    },
    // 文件上传按钮
    cancel() {
      this.isShow = true;
      this.titletwo = "文件上传";
    },
    // 文件上传确定按钮
    cancelOn() {
      this.isShow = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        registrationId: null,
        status: 0,
        aim: null,
        demand: null,
        logStatus: 0,
        checkResult: null,
        resultImgUrlList: null,
        clinicalImpression: null,
        clinicalDiagnosis: null,
        createTime: null,
        excuteStaffId: null,
        logDatetime: null,
        noDrugId: null,
        checkParts: null,
        type: null,
        excuteDeptId: null,
        createStaffId: null,
        logStaffId: null,
        excuteTime: null,
        amount: null,
        resultImgUrlList: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加检查项检验项处置项记录(开立的)";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getNon_drug_item_record(id).then(response => {
        this.form = response.data;
        this.$confirm('确定为 "' + this.form.patient.name + '"登记项目"'+this.form.nonDrug.name+'"吗?', "项目登记", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.form.status=3;
          updateNon_drug_item_record(this.form).then(response =>{
            if (response.code === 200) {
              this.msgSuccess("登记成功");
              this.getList();
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消登记'
          });
        });
      });
    },
    /** 新增检查结果按钮操作 */
    handleAddCheckResult(row) {
      this.reset();
      this.form.id=row.id;
      getNon_drug_item_record(this.form.id).then(response => {
        this.form.checkResult = response.data.checkResult;
      });
      this.open = true;
      this.title = "结果";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.dialogImageUrl = this.ossData.key;
            if(this.dialogImageUrl!=''&&this.dialogImageUrl!=undefined){
              this.form.status= 4;
            }else{
              this.form.status= 3;
            }
            updateNon_drug_item_record_check_result(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("添加成功");
                this.open = false;
                this.clearFiles();
                this.getList();
              }
            });
          } else {
            addNon_drug_item_record(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("添加成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /**药品补录页面*/
    handleBulu(row){
      this.formPre.id=row.id;
      this.registrationId=row.registrationId;
      this.title = "补录处方";
      this.addMed = true;
      this.getDrugList();
      // this.$router.push({path: "/master/medicine_supplement", query: {id: id,registrationId: registrationId}});
      // // 销毁组件，避免通过vue-router再次进入时，仍是上次的history缓存的状态
      // this.$destroy(true);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除检查项检验项处置项记录(开立的)编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delNon_drug_item_record(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有检查项检验项处置项记录(开立的)数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportNon_drug_item_record(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleSuccess(response, file, fileList) {
      console.log(this.ossData.key);
      // 将文件名保存到数据库
      if(this.form.resultImgUrlList!=undefined||this.form.resultImgUrlList!=null){
        this.form.resultImgUrlList += ","+this.ossData.key;
      }else{
        this.form.resultImgUrlList = this.ossData.key;
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      // element ui upload需要一个promise对象
      return new Promise(resolve => {
        return this.getSign().then(data => {
          const suffix = file.name.substring(file.name.lastIndexOf("."))
          this.ossHost = data.host
          // 注意参数的大小写，oss文档就是这样定义的
          // 跟后端返回的变量名不一样，所以只能手动赋值
          this.ossData = {
            key: data.dir + uuidv4() + suffix,
            policy: data.policy,
            OSSAccessKeyId: data.accessKeyId,
            success_action_status: '200', //让服务端返回200，不设置则默认返回204。
            callback: data.callbackBody,
            signature: data.signature,
            expire: data.expire
          }
          resolve(true)
        })
      })
    },
    getSign() {
      // 因为获取签名的方法是异步的，所以通过promise对象执行签名过期判断
      // 确保异步方法执行完成后再执行then中的逻辑，否则可能获取不到值
      return new Promise(resolve => {
        // 判断签名有没有过期，过期了就重新获取签名
        let sign = JSON.parse(sessionStorage.getItem("hncc-oss-sign"));
        let timestamp = Date.parse(new Date()) / 1000;
        if (sign && sign.expire - 3 > timestamp) {
          resolve(sign);
        } else {
          // 重新获取签名并保存
          policy().then(response => {
            sessionStorage.setItem("hncc-oss-sign", JSON.stringify(response.data));
            resolve(response.data);
          });
        }
      })
    }
  }
};
</script>
